<template>
	<view class="login-code">
		<view class="code">
			<input type="text" placeholder="请输入验证码" v-model="code">
			<button class="send-code" @click="sendCode" :disabled="disabled">
				{{codeMsg}}
			</button>
		</view>
		<view class='tel' @click='goNextIndex'>下一步</view>
	</view>
</template>

<script>
	import http from "@/common/api/reqeust.js";
	import {
		mapMutations
	} from 'vuex'

	export default {
		data() {
			return {
				codeMsg: '发送验证码',
				//用户输入的内容
				code: '',
				time: 10,
				disabled: false,
				//得到的验证码
				getCode: "",
				//手机号
				phone: '',
			}
		},
		onReady() {
			this.codeMsg = '重新发送（' + this.time + '）';
			this.sendCode();
		},
		onLoad(e) {
			this.phone = e.phone;
		},
		methods: {
			// 下一步
			goNextIndex() {
				if (this.getCode == this.code) {
					//请求接口==》往数据库增加一条数据
					http.request({
						url: "/user/addUser",
						method: "POST",
						data: {
							phone: this.phone,
							code: this.code
						}
					}).then((res) => {
						//注册成功
						if (res.success) {
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
							uni.redirectTo({
								url: '/pages/login/login'
							})
						}
					}).catch(() => {
						uni.showToast({
							title: '请求失败',
							icon: 'none'
						})
					})
				} else {
					uni.showToast({
						title: "验证码错误",
						icon: "none"
					})
				}
			},

			// 发送验证码
			sendCode() {
				http.request({
					url: '/user/code',
					method: 'post',
					data: {
						phone: this.phone,
					}
				}).then(res => {
					this.getCode = res.code;
					uni.showToast({
						title: this.getCode.toString(),
						icon: 'none'
					})
				})

				// 手机号不存在，发送验证码
				this.disabled = true
				let timer = setInterval(() => {
					--this.time
					this.codeMsg = '重新发送' + this.time
				}, 1000)
				setTimeout(() => {
					clearInterval(timer)
					this.time = 10
					this.disabled = false
					this.codeMsg = '发送验证码'
				}, 10000);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-code {
		padding-top: $pd20;

		.code {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.send-code {
				height: 80rpx;
				line-height: 80rpx;
			}

			margin-bottom: 20rpx;
		}

		.tel {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			color: #FFFFFF;
			background-color: #49BDFB;
			border-radius: 40rpx;
		}
	}
</style>
